document.addEventListener('DOMContentLoaded', function() {
    const uploadForm = document.getElementById('uploadForm');
    const resultSection = document.getElementById('resultSection');
    const originalImage = document.getElementById('originalImage');
    const detectedImage = document.getElementById('detectedImage');
    const detectionsList = document.getElementById('detectionsList');
    const imageUpload = document.getElementById('imageUpload');
    const previewImage = document.getElementById('previewImage');
    const loadingSpinner = document.getElementById('loadingSpinner');

    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('imageUpload');
    uploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        uploadArea.classList.add('dragover');
    });
    uploadArea.addEventListener('dragleave', (e) => {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
    });
    uploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        uploadArea.classList.remove('dragover');
        const files = e.dataTransfer.files;
        if (files.length > 0) {
            fileInput.files = files;
            fileInput.dispatchEvent(new Event('change'));
        }
    });
    // 文件选择时预览图片
    imageUpload.addEventListener('change', function() {
        if (this.files && this.files[0]) {
            const reader = new FileReader();

            reader.onload = function(e) {
                previewImage.src = e.target.result;
                previewImage.style.display = 'inline';
            }

            reader.readAsDataURL(this.files[0]);
        }
    });

    uploadForm.addEventListener('submit', function(e) {
        e.preventDefault();

        // 显示加载动画
        loadingSpinner.style.display = 'block';
        resultSection.style.display = 'none';

        const formData = new FormData(uploadForm);

        // 设置请求头以确保文件名以UTF-8编码
        fetch('/detect', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Accept-Charset': 'utf-8'
            },
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {

                // 隐藏加载动画，显示结果
                loadingSpinner.style.display = 'none';
                resultSection.style.display = 'block';

                // 设置原始图片
                originalImage.src = data.image_path;
                originalImage.style.display = 'inline';
                // 设置检测后的图片
                detectedImage.src = data.results.detected_image;
                detectedImage.style.display = 'inline';
                // 显示检测结果
                detectionsList.innerHTML = '';
                if (data.results.objects.length === 0) {
                    detectionsList.innerHTML = '<div class="detection-item">未检测到任何对象</div>';
                } else {
                    data.results.objects.forEach(object => {
                        const detectionItem = document.createElement('div');
                        detectionItem.className = 'detection-item';
                        detectionItem.innerHTML = `
                            <strong>${object.class}</strong> - 置信度: ${(object.confidence * 100).toFixed(2)}%
                        `;
                        detectionsList.appendChild(detectionItem);
                    });
                }
            } else {
                loadingSpinner.style.display = 'none';
                alert('错误: ' + data.error);
            }
        })
        .catch(error => {
            loadingSpinner.style.display = 'none';
            console.error('错误:', error);
            alert('检测过程中发生错误。');
        });
    });
    previewImage.addEventListener('click', () => {
        previewImage.src = '';
        previewImage.style.display = 'none';
        fileInput.value = '';
    });
});


